package com.yaorange.module.system.service.impl;

import com.yaorange.module.system.entity.vo.PermissionTreeVo;
import com.yaorange.module.system.mapper.SysPermissionMapper;
import com.yaorange.module.system.service.SysPermissionService;
import com.yaorange.pojo.SysPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

@Service
public class SysPermissionServiceImpl implements SysPermissionService {
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Override
    public List<PermissionTreeVo> findPermissionTree() {
        HashMap<Long, PermissionTreeVo> TreeVoMap = new HashMap<>();
        List<SysPermission> permissionList = sysPermissionMapper.findPermissionTree();
        permissionList.stream()
                .map(permission -> {
                    PermissionTreeVo permissionTreeVo = new PermissionTreeVo();
                    permissionTreeVo.setId(permission.getPermId());
                    permissionTreeVo.setLabel(permission.getPermTitle());
                    permissionTreeVo.setChildren(new ArrayList<>());
                    return permissionTreeVo;
                }).forEach(permissionTreeVo -> {
                    TreeVoMap.put(permissionTreeVo.getId(),permissionTreeVo);
                });
        List<PermissionTreeVo> rootTreeVo = new ArrayList<>();
        for (SysPermission permission : permissionList){
            if (null == permission.getPermPid() || 0 == permission.getPermPid()){

                PermissionTreeVo parentVo = TreeVoMap.get(permission.getPermId());
                rootTreeVo.add(parentVo);
            }else {
                PermissionTreeVo parentVo = TreeVoMap.get(permission.getPermPid());
                parentVo.getChildren().add(TreeVoMap.get(permission.getPermId()));

            }
        }
        return rootTreeVo;
    }



    @Override
    public List<SysPermission> findPermissionTreeByUserId(Integer id) {
        return sysPermissionMapper.findPermissionTreeByUserId(id);
    }

    @Override
    public List<SysPermission> findPermissionList() {
        return sysPermissionMapper.findPermissionTree();
    }

}
